package net.enantena.finappsparty2012;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

@SuppressLint("NewApi")
public class Dashboard extends Activity implements OnValueChangeListener, OnNavigationListener {

	//TextView objectiuText;
	TextView textproxpartit;
	TextView data;
	ImageView equipCasaFlag;
	ImageView equipVisitantFlag;
	NumberPicker equipCasa;
	NumberPicker equipVisitant;
	SharedPreferences settings;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dashboard);
		
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		actionBar.setTitle("");
		final String CATEGORIES[] = { "Dies a la platja", "Bulli" };
		SpinnerAdapter mSpinnerAdapter = new ArrayAdapter<Object>(this, R.layout.headline_item, CATEGORIES);
		actionBar.setListNavigationCallbacks(mSpinnerAdapter, this);
		
		settings = getSharedPreferences(Data.sharedprefs, MODE_PRIVATE);
		//String currObjective = settings.getString("objectiu", "-999");
		int currBetCasa = settings.getInt("equipcasa", 0);
		int currBetVisitant = settings.getInt("equipvisitant", 0);
		
		equipCasaFlag = (ImageView) findViewById(R.id.flagcasa);
		equipVisitantFlag = (ImageView) findViewById(R.id.flagvisitant);
		
		//objectiuText = (TextView) findViewById(R.id.objectiuidata);
		textproxpartit = (TextView) findViewById(R.id.textproxpartit);
		data = (TextView) findViewById(R.id.textView1);
		equipCasa = (NumberPicker) findViewById(R.id.equipCasa);
		equipVisitant = (NumberPicker) findViewById(R.id.equipVisitant);
		equipVisitant.setOnValueChangedListener(this);
		equipCasa.setOnValueChangedListener(this);
		equipCasa.setMaxValue(12);
		equipVisitant.setMaxValue(12);
		equipCasa.setMinValue(0);
		equipVisitant.setMinValue(0);
		//objectiuText.setText(currObjective);
		equipVisitant.setValue(currBetVisitant);
		equipCasa.setValue(currBetCasa);
		
		new Futbol().execute("Barcelona");
	}
	
	public class Futbol extends AsyncTask<String, Void, JSONObject> {

		@Override
		protected JSONObject doInBackground(String... params) {
			String equip = params[0];
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Data.partidosJornada + Data.apiKeyResultadosFutbol);

			try {
				HttpResponse response = httpclient.execute(httppost);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONObject jsonResponse = new JSONObject(builder.toString());
				for (int i = 0; i < jsonResponse.getJSONArray("match").length(); i++) {
					JSONObject currObject = jsonResponse.getJSONArray("match").getJSONObject(i);
					if (!currObject.getString("local").equals(equip) && !currObject.getString("visitor").equals(equip)) continue;
					if (currObject.getString("local").equals(equip) || currObject.getString("visitor").equals(equip)) return currObject;
				}
				Log.e("response", builder.toString());

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return new JSONObject();
		}
		
		@Override
		protected void onPostExecute(JSONObject result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				textproxpartit.setText(result.getString("local") + " - " + result.getString("visitor"));
				data.setText(result.getString("date"));
				String localimg = result.getString("local_flag");
				String visitorimg = result.getString("visitor_flag");
//				String hour = currObject.getString("hour");
//				String matchid = currObject.getString("id");
//				String matchresult = currObject.getString("result");
				UrlImageViewHelper.setUrlDrawable(equipCasaFlag, localimg, R.drawable.loading);
				UrlImageViewHelper.setUrlDrawable(equipVisitantFlag, visitorimg, R.drawable.loading);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
		SharedPreferences.Editor editor = settings.edit();
		switch (picker.getId()) {
		case R.id.equipCasa:
			editor.putInt("equipcasa", newVal);
			editor.commit();
			break;
		case R.id.equipVisitant:
			editor.putInt("equipvisitant", newVal);
			editor.commit();
			break;
		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_history:
			startActivity(new Intent(Dashboard.this, History.class));
			break;

		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

}
